/*************************************************************************
	> File Name: 8.7Synchronized--信号量2.c
	> Author: Potter
	> Mail: tobewhatwewant@gmail.com
	> Created Time: 2014年09月18日 星期四 16时23分30秒
 ************************************************************************/

#include<stdio.h>
#include <pthread.h>
#include<semaphore.h>
#define MAXSTACK 100
int stack[MAXSTACK][2];
int size = 0;
sem_t S; /*定义信号量*/

/*从文件file1.dat读取数据，每读1次，信号量加1*/
void RData1(void) {
    FILE * fp = fopen("file1.dat", "r");
    while(! feof(fp)) {
        fscanf(fp, "%d %d", &stack[size][0], &stack[size][1]);
        sem_post(&S);
        ++size;
    }
    fclose(fp);
}

/*从文件file2.dat读取数据*/
void RData2(void) {
    FILE * fp = fopen("file2.dat", "r");
    while(! feof(fp)) {
        fscanf(fp, "%d %d", &stack[size][0], &stack[size][1]);
        sem_post(&S);
        ++ size;
    }
    fclose(fp);
}

/*阻塞等待缓冲区有数据，读取数据后，释放空间，继续等待*/
void CData1(void) {
    while(1) {
        sem_wait(&S);
        fprintf(stdout, "Plus: %d + %d = %d\n", stack[size][0], stack[size][1], stack[size][0] + stack[size][1]);
        -- size;
        sleep(1);
    }
}

void CData2(void) {
    while(1) {
        sem_wait(&S);
        fprintf(stdout, "Multiply: %d * %d = %d\n", stack[size][0], stack[size][1], stack[size][0] * stack[size][1]);
        -- size;
        sleep(1);
    }
}

int main(int argc, char * argv[]) {
    pthread_t tid1, tid2, tid3, tid4;
    sem_init(&S, 0, 0); /*初始化信号量*/
    
    pthread_create(&tid1, NULL, (void *)RData1, NULL);
    pthread_create(&tid2, NULL, (void *)RData2, NULL);
    pthread_create(&tid3, NULL, (void *)CData1, NULL);
    pthread_create(&tid4, NULL, (void *)CData2, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
    pthread_join(tid4, NULL);

    return 0;
}
